﻿using UnityEngine;
using System.Collections;
using DG.Tweening;
using JetBrains.Annotations;

public class Player : MonoBehaviour
{
    private Vector2 targetpos = new Vector2(1, 1);
    public Rigidbody2D rd2D;
    private float restTime = 0.3f;
    private float restTimer;
    private BoxCollider2D collider;
    private Animator animator;
    // Use this for initialization
    void Start()
    {
        //float test = Input.GetAxisRaw("Horizontal");
        //print(test);
        //float test1 = Time.deltaTime;
        //print(test1);
        rd2D = GetComponent<Rigidbody2D>();
        collider = GetComponent<BoxCollider2D>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        rd2D.DOMove(targetpos, 0.3F);
        restTimer += Time.deltaTime;
        if (restTimer < restTime) return;
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
        if (h > 0)
        {
            v = 0;
        }

        if (h != 0 || v != 0)
        {
            GameManager.Instance.ReduceFood(1);
            collider.enabled = false;
            RaycastHit2D hit = Physics2D.Linecast(targetpos, targetpos + new Vector2(h, v));
            collider.enabled = true;
            if (hit.transform == null)
            {
                targetpos += new Vector2(h, v);
            }
            else
            {
                switch (hit.collider.tag)
                {
                    case "outWall":
                        break;
                    case "Wall":
                        animator.SetTrigger("Attack");
                        hit.collider.SendMessage("TakeDamage");
                        break;
                    case "Food":
                        GameManager.Instance.AddFood(10);
                        targetpos += new Vector2(h, v);
                        Destroy(hit.transform.gameObject);
                        break;
                    case "Soda":
                        GameManager.Instance.AddFood(20);
                        targetpos += new Vector2(h, v);
                        Destroy(hit.transform.gameObject);
                        break;
                    case "Enemy":
                        break;
                    case "Exit":
                        enabled = false;
                        break;
                }
            }
            GameManager.Instance.OnPlayerMove();
            restTimer = 0;
        }
        if (GameManager.Instance.food <= 0)
        {
            enabled = false;
        }
    }

    public void TakeDamage(int lossFood)
    {
        GameManager.Instance.ReduceFood(lossFood);
        animator.SetTrigger("Damage");
    }
}
